package com.nexmo.hangman.web.controller;

import com.nexmo.hangman.domain.User;
import com.nexmo.hangman.domain.dto.GameStatusDto;
import com.nexmo.hangman.domain.dto.ManagementGameStatusDto;
import com.nexmo.hangman.domain.dto.UserDto;
import com.nexmo.hangman.service.GameService;
import com.nexmo.hangman.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping(value = "/")
public class HomeController {

    private static final String INDEX_VIEW = "index";
    private static final String GAME_BOARD_VIEW = "game_board";
    private static final String MANAGE_VIEW = "manage";

    private static final String USER_ATTR = "user";
    private static final String GAME_ATTR = "game";

    private final UserService userService;
    private final GameService gameService;


    @Autowired
    public HomeController(UserService userService, GameService gameService) {
        this.userService = userService;
        this.gameService = gameService;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String getWelcomePage(Model model, HttpSession session) {
        String view = INDEX_VIEW;
        UserDto user = (UserDto) session.getAttribute("user");
        if (user != null) {
            view = GAME_BOARD_VIEW;
            GameStatusDto startedGame = (GameStatusDto) session.getAttribute(GAME_ATTR);
            if(startedGame != null) {
                model.addAttribute(GAME_ATTR, startedGame);
            }
        }
        return view;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String postUser(@RequestParam String userName, Model model, HttpSession session) {
        UserDto usr = userService.findByName(userName);
        if(usr == null) {
            model.addAttribute("newUser", true);
            usr = userService.create(userName);
        } else {
            GameStatusDto game = gameService.getUnfinishedGame(usr.getId());
            if (game != null) {
                model.addAttribute("game", game);
            }
        }

        session.setAttribute(USER_ATTR, usr);
        return GAME_BOARD_VIEW;
    }

    @RequestMapping("logout")
    public String logoutUser(HttpSession session) {

        session.removeAttribute(USER_ATTR);
        session.removeAttribute(GAME_ATTR);

        return "redirect:/";
    }

    @RequestMapping("manage")
    public String manage(Model model) {
        List<ManagementGameStatusDto> activeGames =  gameService.getAllActiveGames();
        model.addAttribute("activeGames", activeGames);
        return MANAGE_VIEW;
    }
}
